<?
/**
 * VoiceOne Settings/Rules/outgoing/edit
 *
 * Frontend to provide access to the rules system in voiceone.
 * @package voiceone
 * @subpackage  settings_rules
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
 	sajax_init();
  
  //================ XAJAX ================
	function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_("loading")."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML(); 
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form's params
    $group=$formData["group"];
    $groupType=$formData["kind"];
    $trunkList=$formData["listRight"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Check Group ((not null))
    $groupErr=false;
    if((!isset($formData["group"]))||($group=="")) { 
      //group cannot be null
      $errOut[]= T_("Destination cannot be null");
      $objResponse->addAssign("groupErr","innerHTML",$imgErr);
      $groupErr=true;  
    }
    if($groupErr===false) $objResponse->addAssign("groupErr","innerHTML","");
    // Check Trunk List ((not null))
    $trunkErr=false;
    if(($groupType=GROUP_OF_PHONENUMBER)&&(!is_array($trunkList))) { 
      //trunk list cannot be null
      $errOut[]= T_("Lines list cannot be null");
      $objResponse->addAssign("trunkErr","innerHTML",$imgErr);
      $trunkErr=true;  
    }
    if($trunkErr===false) $objResponse->addAssign("trunkErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML",""); 
      $objResponse->addScript(" document.getElementById('mainform').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
    
  //=================== POST ===================
  if (count($_POST)>0) {
    if (is_array($_POST["listRight"])) $resource=implode("|",$_POST["listRight"]);
    $entry=Array(
      "id"  => $_POST["id"],
      "rule" => $_POST["rule"],
      "priority" => $_POST["priority"],
      "timesegment" => $_POST["timesegment"], 
      "action" => $_POST["action"], 
      "resource" => $resource 
    );
    if (substr($_POST["group"],0,2)=="g_")  $entry["group"]=substr($_POST["group"],2); 
    else $entry["entity"]=$_POST["group"]; 
    if ($_POST["kind"]==GROUP_OF_ALL) $entry["group"]=GROUP_OF_ALL;
    //save the group informations
    $ret=$asterisk->putOutgoingRule($entry);
    if ($ret>0) {
      $alert="<div class=\"AlertGood\">".T_("Rule created")."</div>";
      $_GET["id"]=$ret;
    } else $alert="<div class=\"AlertBad\">".T_("Error: Rule not created")."</div>";
    //return to main page
    goToMainPage($alert);
  }
  
  //================ PAGE LOGIC ================
  //if modify, read the group informations
  if (isset($_GET["id"])) {
    $ret=$asterisk->getOutgoingRule($_GET["id"]);
    if ($err=$asterisk->getError()) die("Error: $err");
    $id=$ret[0]["id"];
    $rule=$ret[0]["rule"];
    $priority=$ret[0]["priority"];
    $timesegment=$ret[0]["timesegment"];  
    $group=$ret[0]["group"]; 
    $entity=$ret[0]["entity"];  
    if($ret[0]["resource"]!="") $resource=split("\|",$ret[0]["resource"]);
    else $resource=array();
    $provider=$ret[0]["provider"];  
    $action=$ret[0]["action"]; 
  }  
  //Get the time segment available
  $tsHtml.="<option value=\"0\">[any time]</option>\n";
  $ret=$asterisk->getTimeSegment(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($ret)) 
  foreach ($ret as $ts) {
    $id=$ts["id"];
    $name=$ts["name"];
    if ($id==$timesegment) $selected=" selected=\"selected\" ";
    else $selected="";
    $tsHtml.="<option value=\"$id\" $selected>$name</option>\n";
  }
  //Get the trunk available
  $ret=$asterisk->getTrunk(0,0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($ret)) 
  foreach ($ret as $tr) {
    $id=$tr["id"];
    $name=$tr["name"];
    if (!@in_array($id,$resource)) $listLeft.="<option value=\"$id\" >$name</option>";    
  }
  //Get the trunk already selected
  if (is_array($resource)) 
  foreach ($resource as $r) {
    $id=$r;
    $tr=$asterisk->getTrunk($id,0);
    $name=$tr[0]["name"];
    if ($id=="0") $name="[any trunk]";
    $listRight.="<option value=\"$id\" >$name</option>";
  }
  //Adjust the trunk list
  if (isset($_GET["id"])) {
    if (!in_array("0",$resource)) $listLeft.="<option value=\"0\">[any trunk]</option>\n";
  } 
  else $listRight.="<option value=\"0\">[any trunk]</option>\n";
  //set GET values
  $id=$_REQUEST["id"];
  $rule=$_REQUEST["rule"];  
  
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/");?>
  <?$sel="outgoing";include("../../navigation.php");?> 
  
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=T_("Outgoing rule")?></h1>
    <h3><a href="../" class="admin" ><?=T_("Return without save")?></a></h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?><?if (isset($_GET["id"])) echo "?id=".$_GET["id"];?>" method="post" onSubmit=" return selectAll(getElementById('listRight'));">
      <!-- TIME SEGMENT -->
    	<h2><?=T_("Time segment")?></h2>
      <p class="blockintro"><?=T_("set the time segment")?></p>
      <div class="block">
        <table>
          <tr>
            <td class="required" width="160"><label for="timesegment"><?=T_("Time segment")?>:</label></td>
            <td colspan="2"><select id="timesegment" name="timesegment" ><?=$tsHtml?></select></td>
          </tr>
        </table>
      </div>
      <!-- DESTINATION -->
      <? echo listGroupEntity($js, $group, $entity);?>      
      <!-- ACTION -->
    	<h2><?=T_("Action")?></h2>
      <p class="blockintro"><?=T_("What do you want to do?")?></p>
      <div class="block">
        <table>
          <tr>
            <td class="required" width="160"><label for="action"><?=T_("Action")?>:</label></td>
            <td >
              <select id="action" name="action">
                <option value="<?=RULE_ALLOW?>" <?if ($action==RULE_ALLOW) echo "selected='selected'";?>><?=T_("ALLOW")?></option>
                <option value="<?=RULE_DENY?>" <?if ($action==RULE_DENY) echo "selected='selected'";?>><?=T_("DENY")?></option>
              </select>
            </td>
          </tr>
        </table>
      </div>
      <!-- TRUNKS -->
      <div id="trunkDiv">
      	<h2><?=T_("Line")?></h2>
        <p class="blockintro"><?=T_("Choose which of the available lines to be used in this rule")?></p>
        <div class="block">
          <table>
            <tr>
              <td class="required">
                <div ><?=T_("Available Resources")?>:</div>
                <select multiple size="5"  name="listLeft[]" id="listLeft"><?=$listLeft?></select>
              </td>
              <td>   
                <div><input type="button" onclick="moveTrunkList( document.getElementById('listLeft'),  document.getElementById('listRight'), false , true)" name="Add     >>"  value="<?=T_("  Add          >")?>" style="width:100px"></div>
                <div><input type="button" onclick="moveTrunkList( document.getElementById('listRight'), document.getElementById('listLeft'),  false )" name="Add     <<"  value="<?=T_("<       Remove  ")?>" style="width:100px"></div>
                <div><input type="button" onclick="moveTrunkList( document.getElementById('listLeft'),  document.getElementById('listRight'), true  , true)" name="Add All >>"  value="<?=T_("  Add All     >>")?>" style="width:100px"></div>
                <div><input type="button" onclick="moveTrunkList( document.getElementById('listRight'), document.getElementById('listLeft'),  true  )" name="Add All <<"  value="<?=T_("<<   Remove All ")?>" style="width:100px"></div>
              </td>
              <td class="required"><div ><?=T_("Ports added")?>:&nbsp;&nbsp;<span id="trunkErr"></span></div>
                <div style="float: left">
                  <input type="image"  src="<?=$relBasePath?>public/img/icon_up.gif"  onclick="moveOptions ( document.getElementById('listRight'), -1); return false" name="Up"  value="Down" style="display: block">
                  <input type="image"  src="<?=$relBasePath?>public/img/icon_down.gif"  onclick="moveOptions ( document.getElementById('listRight'), 1); return false;" name="Down"  value="Down" style="display: block">
                </div>
                  <select multiple size="5" name="listRight[]" id="listRight"><?=$listRight?></select>
              </td>
            </tr>
          </table>
        </div>
      </div>      
      <!-- INPUT BUTTONS -->
      <?=$numHidden?>      
      <div class="action">
        <input type="hidden" name="id" value="<?=$id?>" />
        <input type="hidden" name="rule" value="<?=$rule?>" />
        <input type="hidden" name="priority" value="<?=$priority?>" />
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" selectAll(getElementById('listRight')); document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>  
      <!--
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="return checkDestination();" />
       -->
      </div>
    </form>
  </div>  
  
  
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
        <div class="Sidebar">
          <h1><?=T_("Edit the Rule")?></h1>
          <p><?=T_("To be done...")?>
        </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();
  $smarty->assign("section", "rules");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>

